import QtQuick 2.12
import QtQuick.Controls 2.5
import QtQuick.Layouts 1.0
import QtQuick.Window 2.14
import Qt.labs.platform 1.1

Window {
    objectName: "screenshot"
    id: root

    readonly property int borderMargin: 3
    readonly property color tranparentColor: "transparent"       //透明色
    readonly property color blurryColor: Qt.rgba(0,0,0,0.3)      //模糊色
    readonly property color selectBorderColor: "green"           //边框色

    color: tranparentColor
    visibility: ApplicationWindow.FullScreen
    flags: Qt.FramelessWindowHint

    Loader {
        id:solidLoader
    }

    onWindowStateChanged: {
        screenshotInit()
    }

    function screenshotInit() {
        // 从C++获取当前屏幕截图
        screenshotImage.source = "image://pixmap?stamp=" + new Date()
        // 初始化各组件状态
        selectionRect.width = 0
        selectionRect.height = 0
        selectionRect.x = 0
        selectionRect.y = 0
        selectionRect.visible = false
        functionRect.visible = false
        paintSetting.visible = false
        reatImage.source = "qrc:/image/res/rectangle_0.png"
        circleImage.source = "qrc:/image/res/circle_0.png"
        penImage.source = "qrc:/image/res/pen_0.png"
        fontImage.source = "qrc:/image/res/font_0.png"
        arrowImage.source = "qrc:/image/res/cc-arrow-up_0.png"
        mosaicImage.source = "qrc:/image/res/mosaic_0.png"
        currentColor = "red"
        currentLineWidth = 2
        currentTool = ""
        currentShape = ({})
        undoStack = []
        mainCanvas.requestPaint()
    }

    Shortcut {
        context: Qt.ApplicationShortcut
        sequence: "esc"
        onActivated: {
            close()
        }
    }

    Image {
        source: "image://pixmap?stamp=" + new Date()
        id: screenshotImage
        anchors.fill: parent
    }

    // 画图参数
    property string currentColor: "red"
    property int currentLineWidth: 2
    property string currentTool: ""
    property var undoStack: []
    property var activeTextItems: [] // 存储活动的文本框

    // 离屏渲染画布
    Canvas {
        id: offscreenCanvas
        visible: false
    }

    // 主绘图画布
    Canvas {
        id: mainCanvas
        anchors.fill: parent
        z: 10

        onPaint: {
            var ctx = getContext("2d")
            ctx.clearRect(0, 0, width, height)

            // 绘制所有已保存的图形
            for (var i = 0; i < undoStack.length; i++) {
                drawShape(ctx, undoStack[i])
            }

            // 绘制当前正在操作的图形
            if (currentShape.type) {
                drawShape(ctx, currentShape)
            }
        }

        function drawShape(ctx, shape) {
            ctx.save()
            ctx.strokeStyle = shape.color
            ctx.lineWidth = shape.lineWidth
            ctx.fillStyle = shape.fillColor || "transparent"
            ctx.lineCap = "round"  // 使线条端点更圆滑
            ctx.lineJoin = "round"  // 使线条连接处更圆滑

            switch(shape.type) {
            case "rect":
                ctx.strokeRect(shape.x, shape.y, shape.width, shape.height)
                break
            case "ellipse":
                ctx.beginPath()
                ctx.ellipse(shape.x, shape.y, shape.width, shape.height)
                ctx.stroke()
                break
            case "line":
                ctx.beginPath()
                ctx.moveTo(shape.startX, shape.startY)
                ctx.lineTo(shape.endX, shape.endY)
                ctx.stroke()
                break
            case "arrow":
                drawArrow(ctx, shape)
                break;
            case "text":
                ctx.font = `${shape.fontSize}px sans-serif`
                ctx.fillStyle = shape.color
                ctx.fillText(shape.text, shape.x, shape.y)
                break
            case "paint":
                // 绘制自由路径
                ctx.beginPath()
                if (shape.points && shape.points.length > 0) {
                    ctx.moveTo(shape.points[0].x, shape.points[0].y)
                    for (var i = 1; i < shape.points.length; i++) {
                        ctx.lineTo(shape.points[i].x, shape.points[i].y)
                    }
                }
                ctx.stroke()
                break
            case "mosaic":
                // 绘制马赛克
                drawMosaic(ctx, shape)
                break
            }
            ctx.restore()
        }

        function drawArrow(ctx, arrow) {
            // 计算箭头角度
            var angle = Math.atan2(arrow.endY - arrow.startY,
                                  arrow.endX - arrow.startX)
            var arrowLength = 7.5 * arrow.lineWidth

            // 计算箭杆终点（减去箭头长度）
            var shaftEndX = arrow.endX - (arrowLength - 5) * Math.cos(angle)
            var shaftEndY = arrow.endY - (arrowLength - 5) * Math.sin(angle)

            // 绘制箭杆
            ctx.beginPath()
            ctx.moveTo(arrow.startX, arrow.startY)
            ctx.lineTo(shaftEndX, shaftEndY)
            ctx.stroke()

            // 绘制箭头三角形
            ctx.beginPath()
            ctx.moveTo(arrow.endX, arrow.endY)
            ctx.lineTo(
                arrow.endX - arrowLength * Math.cos(angle - Math.PI/6),
                arrow.endY - arrowLength * Math.sin(angle - Math.PI/6)
            )
            ctx.lineTo(
                arrow.endX - arrowLength * Math.cos(angle + Math.PI/6),
                arrow.endY - arrowLength * Math.sin(angle + Math.PI/6)
            )
            ctx.closePath()
            ctx.fillStyle = arrow.color
            ctx.fill()
        }

        function drawMosaic(ctx, mosaic) {
            if (!mosaic.points || mosaic.points.length === 0) return;

            // 设置马赛克样式
            ctx.save();
            ctx.strokeStyle = "black";
            ctx.lineWidth = 1;

            // 获取截图图像的像素数据
            var imageData = getImageDataFromScreenshot();
            if (!imageData) return;

            // 绘制马赛克点
            for (var i = 0; i < mosaic.points.length; i++) {
                var point = mosaic.points[i];
                var size = mosaic.size;

                // 计算马赛克块中心点
                var centerX = Math.round(point.x);
                var centerY = Math.round(point.y);

                // 获取中心点颜色
                var color = getPixelColor(imageData, centerX, centerY);
                if (!color) continue;

                // 绘制马赛克方块
                ctx.fillStyle = color;
                ctx.fillRect(point.x - size/2, point.y - size/2, size, size);
            }

            ctx.restore();
        }

        function getImageDataFromScreenshot() {
            // 使用离屏渲染
            offscreenCanvas.width = screenshotImage.width;
            offscreenCanvas.height = screenshotImage.height;

            // 等待canvas准备好
            var ctx = offscreenCanvas.getContext('2d');
            ctx.drawImage(screenshotImage, 0, 0);

            // 获取图像数据
            return ctx.getImageData(0, 0, screenshotImage.width, screenshotImage.height);
        }

        function getPixelColor(imageData, x, y) {
            // 确保坐标在有效范围内
            if (x < 0 || x >= imageData.width || y < 0 || y >= imageData.height) {
                return null;
            }

            // 计算像素索引
            var index = (y * imageData.width + x) * 4;

            // 获取RGBA值
            var r = imageData.data[index];
            var g = imageData.data[index + 1];
            var b = imageData.data[index + 2];
            var a = imageData.data[index + 3];

            // 返回CSS颜色字符串
            return Qt.rgba(r/255, g/255, b/255, a/255);
        }
    }

    // 当前正在绘制的图形
    property var currentShape: ({})

    // 文本框容器（放在Canvas之上）
    Item {
        id: textInputContainer
        anchors.fill: parent
        z: 20 // 确保在Canvas之上
    }

    // 文本输入框组件
    Component {
        id: textInputComponent

        Rectangle {
            id: resizableTextInput
            width: 200
            height: 80
            border.color: "#cccccc"
            border.width: 1
            radius: 4

            property bool isActive: true
            property alias textField: textField

            // 1. 文本输入框主体
            TextArea {
                id: textField
                anchors {
                    fill: parent
                    margins: 5
                }
                wrapMode: Text.Wrap
                background: null
                font.pixelSize: 7 * currentLineWidth
                color: root.currentColor

                Keys.onReturnPressed: {
                    if (event.modifiers & Qt.ControlModifier) {
                        finishTextInput();
                    }
                }
                Keys.onEnterPressed: {
                    if (event.modifiers & Qt.ControlModifier) {
                        finishTextInput();
                    }
                }
                Keys.onEscapePressed: {
                    cancelTextInput();
                }

                // 支持文本变化事件
                onTextChanged: {
                    // 动态调整文本框大小
                    if (contentHeight + 10 > resizableTextInput.height) {
                        resizableTextInput.height = contentHeight + 10;
                    }
                }
            }

            // 2. 右下角拖拽手柄
            Rectangle {
                id: dragHandle
                width: 12
                height: 12
                color: "#21be2b"
                radius: 2
                anchors {
                    right: parent.right
                    bottom: parent.bottom
                    margins: 2
                }

                MouseArea {
                    id: resizeArea
                    anchors.fill: parent
                    cursorShape: Qt.SizeFDiagCursor
                    preventStealing: true

                    property point startPos: Qt.point(0, 0)

                    onPressed: (mouse) => {
                        startPos = Qt.point(mouse.x, mouse.y);
                    }

                    onPositionChanged: (mouse) => {
                        var deltaX = mouse.x - startPos.x;
                        var deltaY = mouse.y - startPos.y;

                        resizableTextInput.width += deltaX;
                        resizableTextInput.height += deltaY;

                        resizableTextInput.width = Math.max(50, resizableTextInput.width);
                        resizableTextInput.height = Math.max(30, resizableTextInput.height);
                    }
                }
            }

            // 3. 完成按钮（右上角）
            Rectangle {
                width: 20
                height: 20
                color: "green"
                radius: 10
                anchors {
                    top: parent.top
                    right: parent.right
                    margins: 5
                }

                Text {
                    text: "✓"
                    color: "white"
                    anchors.centerIn: parent
                    font.bold: true
                }

                MouseArea {
                    anchors.fill: parent
                    onClicked: finishTextInput()
                }
            }

            // 4. 取消按钮（左上角）
            Rectangle {
                width: 20
                height: 20
                color: "red"
                radius: 10
                anchors {
                    top: parent.top
                    left: parent.left
                    margins: 5
                }

                Text {
                    text: "✕"
                    color: "white"
                    anchors.centerIn: parent
                    font.bold: true
                }

                MouseArea {
                    anchors.fill: parent
                    onClicked: cancelTextInput()
                }
            }

            // 鼠标穿透处理
            MouseArea {
                anchors.fill: parent
                acceptedButtons: Qt.NoButton
                propagateComposedEvents: true
                onPressed: (mouse) => mouse.accepted = false
                onPositionChanged: (mouse) => mouse.accepted = false
            }

            function finishTextInput() {
                if (textField.text.trim() !== "") {
                    // 保存文本到画布
                    var textObj = {
                        type: "text",
                        text: textField.text,
                        x: resizableTextInput.x + 5,
                        y: resizableTextInput.y + 5,
                        color: root.currentColor,
                        fontSize: textField.font.pixelSize
                    };
                    root.undoStack.push(textObj);
                    mainCanvas.requestPaint();
                }
                destroyTextInput();
            }

            function cancelTextInput() {
                destroyTextInput();
            }

            function destroyTextInput() {
                // 从活动文本列表中移除
                var index = root.activeTextItems.indexOf(resizableTextInput);
                if (index !== -1) {
                    root.activeTextItems.splice(index, 1);
                }
                resizableTextInput.destroy();
            }

            Component.onCompleted: {
                textField.forceActiveFocus();
                root.activeTextItems.push(resizableTextInput);
            }
        }
    }

    // 全局鼠标区域用于完成文本输入
    MouseArea {
        anchors.fill: parent
        propagateComposedEvents: true
        enabled: root.activeTextItems.length > 0
        onClicked: {
            // 检查点击是否在文本框内
            var clickedInside = false;
            for (var i = 0; i < root.activeTextItems.length; i++) {
                var textItem = root.activeTextItems[i];
                if (textItem.isActive && textItem.contains(Qt.point(mouseX, mouseY))) {
                    clickedInside = true;
                    break;
                }
            }

            // 如果点击在文本框外，完成所有活动文本输入
            if (!clickedInside) {
                for (var j = 0; j < root.activeTextItems.length; j++) {
                    var item = root.activeTextItems[j];
                    if (item.isActive) {
                        item.finishTextInput();
                    }
                }
            }
        }
    }

    //四个阴影区域，笼罩未选择区域
    //一个选择区域
    Rectangle{
        id: topRect
        anchors{
            top: parent.top
            left: parent.left
        }
        width: parent.width
        height: selectionRect.y
        color: blurryColor
    }

    Rectangle{
        id: leftRect
        anchors{
            top: topRect.bottom
            left: parent.left
        }
        width: selectionRect.x
        height: parent.height - topRect.height - bottomRect.height
        color: blurryColor
    }

    Rectangle{
        id: rightRect
        anchors{
            top: topRect.bottom
            right: parent.right
        }
        width: parent.width - leftRect.width - selectionRect.width
        height: leftRect.height
        color: blurryColor
    }

    Rectangle{
        id: bottomRect
        anchors{
            bottom: parent.bottom
            left: parent.left
        }
        width: parent.width
        height: parent.height - topRect.height - selectionRect.height
        color: blurryColor
    }

    MouseArea {
        id: mainMouseArea
        anchors.fill: parent
        cursorShape: Qt.CrossCursor
        property int startX: 0
        property int startY: 0
        property int endX: 0
        property int endY: 0

        onPressed: function (mouse){
            startX = mouse.x;
            startY = mouse.y;
            selectionRect.width = 0;
            selectionRect.height = 0;
            selectionRect.visible = true;
        }
        onPositionChanged: function (mouse){
            if (pressed) {
                endX = mouse.x;
                endY = mouse.y;
                selectionRect.width = Math.abs(endX - startX);
                selectionRect.height = Math.abs(endY - startY);
                selectionRect.x = Math.min(startX, endX);
                selectionRect.y = Math.min(startY, endY);
            }
        }
        onReleased: function (mouse){
            selectionRect.updateStartAndEndPoint();
            if (selectionRect.height + selectionRect.y >= Screen.height - 70) {
                functionRect.anchors.top = selectionRect.top
                if (selectionRect.y >= 70) {
                    functionRect.anchors.topMargin = -70
                }
            }
            else {
                functionRect.anchors.top = selectionRect.bottom
                functionRect.anchors.topMargin = 0
            }

            functionRect.visible = true;
        }
    }

    Rectangle {
        id: selectionRect

        property var startPoint
        property var endPoint

        function updateStartAndEndPoint() {
            startPoint = Qt.point(x, y);
            endPoint = Qt.point(x + width, y + height);
        }

        visible: false
        border.color: selectBorderColor
        border.width: 1
        color: tranparentColor

        MouseArea {
            id: dragItem
            enabled: currentTool == ""
            anchors.fill: parent
            anchors.margins: 12 * 2
            cursorShape: Qt.SizeAllCursor
            drag.target: parent
            onPositionChanged: {
                selectionRect.updateStartAndEndPoint();
                if (selectionRect.height + selectionRect.y >= Screen.height - 70) {
                    functionRect.anchors.top = selectionRect.top
                    if (selectionRect.y >= 70) {
                        functionRect.anchors.topMargin = -70
                    }
                }
                else {
                    functionRect.anchors.top = selectionRect.bottom
                    functionRect.anchors.topMargin = 0
                }

                functionRect.visible = true;
            }
        }

        // 鼠标交互处理
        MouseArea {
            anchors.fill: parent
            enabled: currentTool !== ""
            visible: currentTool !== ""
            onPressed: {
                console.log("x="+mouseX+",y="+mouseY+",px="+parent.x+",py="+parent.y+"tool="+currentTool)
                switch(currentTool) {
                case "rect":
                case "ellipse":
                    currentShape = {
                        type: currentTool,
                        x: mouseX + parent.x,
                        y: mouseY + parent.y,
                        width: 0,
                        height: 0,
                        color: currentColor,
                        lineWidth: currentLineWidth
                    }
                    break
                case "line":
                case "arrow":
                    currentShape = {
                        type: currentTool,
                        startX: mouseX + parent.x,
                        startY: mouseY + parent.y,
                        endX: mouseX + parent.x,
                        endY: mouseY + parent.y,
                        color: currentColor,
                        lineWidth: currentLineWidth
                    }
                    break
                case "paint":
                    // 初始化画笔路径
                    currentShape = {
                        type: "paint",
                        points: [Qt.point(mouseX + parent.x, mouseY + parent.y)],
                        color: currentColor,
                        lineWidth: currentLineWidth
                    }
                    break
                case "mosaic":
                    // 初始化马赛克路径
                    currentShape = {
                        type: "mosaic",
                        points: [Qt.point(mouseX + parent.x, mouseY + parent.y)],
                        size: currentLineWidth * 5
                    }
                    break
                case "text":
                    // 创建可调整大小的文本框
                    var textInput = textInputComponent.createObject(
                        textInputContainer,
                        {
                            x: mouseX + parent.x,
                            y: mouseY + parent.y
                        }
                    )
                    break
                }
            }

            onPositionChanged: {
                if (currentTool === "text") return; // 跳过处理
                if (currentShape.type === "rect" || currentShape.type === "ellipse") {
                    currentShape.width = mouseX + parent.x - currentShape.x
                    currentShape.height = mouseY + parent.y - currentShape.y
                    mainCanvas.requestPaint()
                }
                else if (currentShape.type === "line" || currentShape.type === "arrow") {
                    currentShape.endX = mouseX + parent.x
                    currentShape.endY = mouseY + parent.y
                    mainCanvas.requestPaint()
                }
                else if (currentShape.type === "paint" || currentShape.type === "mosaic") {
                    // 添加新点到画笔路径
                    currentShape.points.push(Qt.point(mouseX + parent.x, mouseY + parent.y))
                    mainCanvas.requestPaint()
                }
            }

            onReleased: {
                if (currentShape.type) {
                    undoStack.push(currentShape)
                    currentShape = ({});
                }
            }
        }

        Item{
            id: resizeBorderItem
            anchors.centerIn: parent
            width: parent.width + borderMargin * 2
            height: parent.height + borderMargin * 2
        }

        //LeftTop
        CusDragRect{
            id: dragLeftTop
            anchors{
                left: resizeBorderItem.left
                top: resizeBorderItem.top
            }
            visible: selectionRect.visible
            callBackFunc : selectionRect.updateStartAndEndPoint
            posType: posLeftTop

            onSigPosChanged: function(mousePoint){
                var point = mapToGlobal(mousePoint);
                selectionRect.x = Math.min(point.x, selectionRect.endPoint.x);
                selectionRect.y = Math.min(point.y, selectionRect.endPoint.y);
                selectionRect.width = Math.max(selectionRect.endPoint.x, point.x)  - selectionRect.x;
                selectionRect.height = Math.max(selectionRect.endPoint.y, point.y) - selectionRect.y;
            }
        }

        //LeftBottom
        CusDragRect{
            id: dragLeftBottom
            anchors{
                left: resizeBorderItem.left
                bottom: resizeBorderItem.bottom
            }
            visible: selectionRect.visible
            callBackFunc : selectionRect.updateStartAndEndPoint
            posType: posLeftBottom

            onSigPosChanged: function(mousePoint){
                var point = mapToGlobal(mousePoint);
                selectionRect.x = Math.min(point.x, selectionRect.endPoint.x);
                selectionRect.y = Math.min(point.y, selectionRect.startPoint.y);
                selectionRect.width = Math.max(selectionRect.endPoint.x, point.x)  - selectionRect.x;
                selectionRect.height = Math.max(selectionRect.startPoint.y, point.y) - selectionRect.y;
            }
        }

        //RightTop
        CusDragRect{
            id: dragRightTop
            anchors{
                right: resizeBorderItem.right
                top: resizeBorderItem.top
            }
            visible: selectionRect.visible
            callBackFunc : selectionRect.updateStartAndEndPoint
            posType: posRightTop

            onSigPosChanged: function(mousePoint){
                var point = mapToGlobal(mousePoint);
                selectionRect.x = Math.min(point.x, selectionRect.startPoint.x);
                selectionRect.y = Math.min(point.y, selectionRect.endPoint.y);
                selectionRect.width = Math.max(selectionRect.startPoint.x, point.x)  - selectionRect.x;
                selectionRect.height = Math.max(selectionRect.endPoint.y, point.y) - selectionRect.y;
            }
        }

        //RightBottom
        CusDragRect{
            id: dragRightBottom
            anchors{
                right: resizeBorderItem.right
                bottom: resizeBorderItem.bottom
            }
            visible: selectionRect.visible
            callBackFunc : selectionRect.updateStartAndEndPoint
            posType: posRightBottom

            onSigPosChanged: function(mousePoint){
                var point = mapToGlobal(mousePoint);
                selectionRect.x = Math.min(point.x, selectionRect.startPoint.x);
                selectionRect.y = Math.min(point.y, selectionRect.startPoint.y);
                selectionRect.width = Math.max(selectionRect.startPoint.x, point.x)  - selectionRect.x;
                selectionRect.height = Math.max(selectionRect.startPoint.y, point.y) - selectionRect.y;
            }
        }

        //Top
        CusDragRect{
            id: dragTop
            anchors{
                top: resizeBorderItem.top
                horizontalCenter: resizeBorderItem.horizontalCenter
            }
            visible: selectionRect.visible
            callBackFunc : selectionRect.updateStartAndEndPoint
            posType: posTop

            onSigPosChanged: function(mousePoint){
                var point = mapToGlobal(mousePoint);
                selectionRect.y = Math.min(point.y, selectionRect.endPoint.y);
                selectionRect.height = Math.max(selectionRect.endPoint.y, point.y) - selectionRect.y;
            }
        }

        //Bottom
        CusDragRect{
            id: dragBottom
            anchors{
                bottom: resizeBorderItem.bottom
                horizontalCenter: resizeBorderItem.horizontalCenter
            }
            visible: selectionRect.visible
            callBackFunc : selectionRect.updateStartAndEndPoint
            posType: posBottom

            onSigPosChanged: function(mousePoint){
                var point = mapToGlobal(mousePoint);
                selectionRect.y = Math.min(point.y, selectionRect.startPoint.y);
                selectionRect.height = Math.max(selectionRect.startPoint.y, point.y) - selectionRect.y;
            }
        }

        //Left
        CusDragRect{
            id: dragLeft
            anchors{
                left: resizeBorderItem.left
                verticalCenter: resizeBorderItem.verticalCenter
            }
            visible: selectionRect.visible
            callBackFunc : selectionRect.updateStartAndEndPoint
            posType: posLeft

            onSigPosChanged: function(mousePoint){
                var point = mapToGlobal(mousePoint);
                selectionRect.x = Math.min(point.x, selectionRect.endPoint.x);
                selectionRect.width = Math.max(selectionRect.endPoint.x, point.x)  - selectionRect.x;

            }
        }

        //Right
        CusDragRect{
            id: dragRight
            anchors{
                right: resizeBorderItem.right
                verticalCenter: resizeBorderItem.verticalCenter
            }
            visible: selectionRect.visible
            callBackFunc : selectionRect.updateStartAndEndPoint
            posType: posLeft

            onSigPosChanged: function(mousePoint){
                var point = mapToGlobal(mousePoint);
                selectionRect.x = Math.min(point.x, selectionRect.startPoint.x);
                selectionRect.width = Math.max(selectionRect.startPoint.x, point.x)  - selectionRect.x;

            }
        }
    }

    Rectangle{
        id: functionRect
        width: 504
        height: 30
        visible: false
        radius: 5
        anchors{
            top: selectionRect.bottom
            topMargin: 3
            right:selectionRect.right
        }

        MouseArea {
            anchors.fill: parent
        }

        RowLayout {
        id: layout
        anchors.fill: parent
        anchors.leftMargin: 20
        anchors.rightMargin: 20
        spacing: 20
            Item {
                height: 24
                width: 24
                Image {
                    id: reatImage
                    height: 24
                    width: 24
                    source: "qrc:/image/res/rectangle_0.png"
                }
                MouseArea {
                    anchors.fill: parent
                    hoverEnabled: true
                    onClicked: {
                        paintSetting.visible = true
                        paintSettingCursor.anchors.leftMargin = parent.x + 12 + 15
                        reatImage.source = "qrc:/image/res/rectangle.png"
                        circleImage.source = "qrc:/image/res/circle_0.png"
                        penImage.source = "qrc:/image/res/pen_0.png"
                        fontImage.source = "qrc:/image/res/font_0.png"
                        arrowImage.source = "qrc:/image/res/cc-arrow-up_0.png"
                        mosaicImage.source = "qrc:/image/res/mosaic_0.png"
                        currentTool = "rect"
                    }
                    ToolTip {
                        visible: parent.containsMouse
                        text: "矩形"
                        delay: 500
                    }
                }
            }

            Item {
                height: 24
                width: 24
                Image {
                    id: circleImage
                    height: 24
                    width: 24
                    source: "qrc:/image/res/circle_0.png"
                }
                MouseArea {
                    anchors.fill: parent
                    hoverEnabled: true
                    onClicked: {
                        paintSetting.visible = true
                        paintSettingCursor.anchors.leftMargin = parent.x + 12 + 15
                        reatImage.source = "qrc:/image/res/rectangle_0.png"
                        circleImage.source = "qrc:/image/res/circle.png"
                        penImage.source = "qrc:/image/res/pen_0.png"
                        fontImage.source = "qrc:/image/res/font_0.png"
                        arrowImage.source = "qrc:/image/res/cc-arrow-up_0.png"
                        mosaicImage.source = "qrc:/image/res/mosaic_0.png"
                        currentTool = "ellipse"
                    }
                    ToolTip {
                        visible: parent.containsMouse
                        text: "椭圆"
                        delay: 500
                    }
                }
            }

            Item {
                height: 24
                width: 24
                Image {
                    id: penImage
                    height: 24
                    width: 24
                    source: "qrc:/image/res/pen_0.png"
                }
                MouseArea {
                    anchors.fill: parent
                    hoverEnabled: true
                    onClicked: {
                        paintSetting.visible = true
                        paintSettingCursor.anchors.leftMargin = parent.x + 12 + 15
                        reatImage.source = "qrc:/image/res/rectangle_0.png"
                        circleImage.source = "qrc:/image/res/circle_0.png"
                        penImage.source = "qrc:/image/res/pen.png"
                        fontImage.source = "qrc:/image/res/font_0.png"
                        arrowImage.source = "qrc:/image/res/cc-arrow-up_0.png"
                        mosaicImage.source = "qrc:/image/res/mosaic_0.png"
                        currentTool = "paint"
                    }
                    ToolTip {
                        visible: parent.containsMouse
                        text: "笔"
                        delay: 500
                    }
                }
            }

            Item {
                height: 24
                width: 24
                Image {
                    id: fontImage
                    height: 24
                    width: 24
                    source: "qrc:/image/res/font_0.png"
                }
                MouseArea {
                    anchors.fill: parent
                    hoverEnabled: true
                    onClicked: {
                        paintSetting.visible = true
                        paintSettingCursor.anchors.leftMargin = parent.x + 12 + 15
                        reatImage.source = "qrc:/image/res/rectangle_0.png"
                        circleImage.source = "qrc:/image/res/circle_0.png"
                        penImage.source = "qrc:/image/res/pen_0.png"
                        fontImage.source = "qrc:/image/res/font.png"
                        arrowImage.source = "qrc:/image/res/cc-arrow-up_0.png"
                        mosaicImage.source = "qrc:/image/res/mosaic_0.png"
                        currentTool = "text"
                    }
                    ToolTip {
                        visible: parent.containsMouse
                        text: "文本"
                        delay: 500
                    }
                }
            }

            Item {
                height: 24
                width: 24
                Image {
                    id: arrowImage
                    height: 24
                    width: 24
                    source: "qrc:/image/res/cc-arrow-up_0.png"
                }
                MouseArea {
                    anchors.fill: parent
                    hoverEnabled: true
                    onClicked: {
                        paintSetting.visible = true
                        paintSettingCursor.anchors.leftMargin = parent.x + 12 + 15
                        reatImage.source = "qrc:/image/res/rectangle_0.png"
                        circleImage.source = "qrc:/image/res/circle_0.png"
                        penImage.source = "qrc:/image/res/pen_0.png"
                        fontImage.source = "qrc:/image/res/font_0.png"
                        arrowImage.source = "qrc:/image/res/cc-arrow-up.png"
                        mosaicImage.source = "qrc:/image/res/mosaic_0.png"
                        currentTool = "arrow"
                    }
                    ToolTip {
                        visible: parent.containsMouse
                        text: "箭头"
                        delay: 500
                    }
                }
            }

            Item {
                height: 24
                width: 24
                Image {
                    id: mosaicImage
                    height: 24
                    width: 24
                    source: "qrc:/image/res/mosaic_0.png"
                }
                MouseArea {
                    anchors.fill: parent
                    hoverEnabled: true
                    onClicked: {
                        mosaicImage.source = "qrc:/image/res/mosaic.png"
                        reatImage.source = "qrc:/image/res/rectangle_0.png"
                        circleImage.source = "qrc:/image/res/circle_0.png"
                        penImage.source = "qrc:/image/res/pen_0.png"
                        fontImage.source = "qrc:/image/res/font_0.png"
                        arrowImage.source = "qrc:/image/res/cc-arrow-up_0.png"
                        currentTool = "mosaic"
                        paintSetting.visible = false
                    }
                    ToolTip {
                        visible: parent.containsMouse
                        text: "马赛克"
                        delay: 500
                    }
                }
            }

            Item {
                height: 24
                width: 24
                Image {
                    id: cancelImage
                    height: 24
                    width: 24
                    source: "qrc:/image/res/cancel_0.png"
                }
                MouseArea {
                    anchors.fill: parent
                    hoverEnabled: true
                    onPressed: {
                        cancelImage.source = "qrc:/image/res/cancel.png"
                    }
                    onReleased: {
                        cancelImage.source = "qrc:/image/res/cancel_0.png"
                    }
                    onClicked: {
                        undoStack.pop()
                        currentShape = ({});
                        mainCanvas.requestPaint()
                    }
                    ToolTip {
                        visible: parent.containsMouse
                        text: "撤销"
                        delay: 500
                    }
                }
            }

            Item {
                height: 24
                width: 24
                Image {
                    id: saveImage
                    height: 24
                    width: 24
                    source: "qrc:/image/res/save_0.png"
                }
                MouseArea {
                    anchors.fill: parent
                    hoverEnabled: true
                    onPressed: {
                        saveImage.source = "qrc:/image/res/save.png"
                    }
                    onReleased: {
                        saveImage.source = "qrc:/image/res/save_0.png"
                    }
                    onClicked: {
                        captureScreenshot(selectionRect.x + 3, selectionRect.y + 3, selectionRect.width - 8, selectionRect.height - 8)
                        saveDialog.open()                        
                    }
                }
            }

            Item {
                height: 24
                width: 24
                Image {
                    id: solidImage
                    height: 24
                    width: 24
                    source: "qrc:/image/res/thumbtack-solid_0.png"
                }
                MouseArea {
                    anchors.fill: parent
                    onPressed: {
                        solidImage.source = "qrc:/image/res/thumbtack-solid.png"
                    }
                    onReleased: {
                        solidImage.source = "qrc:/image/res/thumbtack-solid_0.png"
                    }
                    onClicked: {
                        captureScreenshot(selectionRect.x + 3, selectionRect.y + 3, selectionRect.width - 8, selectionRect.height - 8)
                        solidLoader.setSource("qrc:/qml/qml/Solid.qml", {"w": selectionRect.width - 8, "h": selectionRect.height - 8})
                        solidLoader.focus = true
                        close()
                    }
                }
            }

            Item {
                height: 24
                width: 24
                Image {
                    height: 24
                    width: 24
                    source: "qrc:/image/res/cancel_1.png"
                }
                MouseArea {
                    anchors.fill: parent
                    onClicked: {
                        close()
                    }
                }
            }

            Item {
                height: 24
                width: 24
                Image {
                    height: 24
                    width: 24
                    source: "qrc:/image/res/complete.png"
                }
                MouseArea {
                    anchors.fill: parent
                    onClicked: {
                        captureScreenshot(selectionRect.x + 3, selectionRect.y + 3, selectionRect.width - 8, selectionRect.height - 8)
                        close()
                    }
                }
            }
        }
    }

    Rectangle {
        id: paintSetting
        width: 242
        height: 30
        visible: false
        radius: 5
        anchors{
            top: functionRect.bottom
            topMargin: 10
            left:functionRect.left
        }

        MouseArea {
            anchors.fill: parent
        }

        Rectangle {
            id: paintSettingCursor
            width: 10
            height: 10
            anchors{
                top: paintSetting.top
                topMargin: -5
                left: paintSetting.left
                leftMargin: 20
            }
            rotation: 45
        }

        RowLayout {
            anchors.fill: parent
            anchors.leftMargin: 5
            anchors.rightMargin: 5
            spacing: 10
            z: 99

            Item {
                width: 10
                height: 10
                Layout.leftMargin: 10
                Rectangle {
                    id: lineWidth_1
                    width: 5
                    height: 5
                    radius: 5
                    color: "#1296db"
                    anchors.centerIn: parent
                }
                MouseArea {
                    anchors.fill: parent
                    onClicked: {
                        lineWidth_1.color = "#1296db"
                        lineWidth_2.color = "#bfbfbf"
                        lineWidth_3.color = "#bfbfbf"
                        currentLineWidth = 2
                    }
                }
            }

            Rectangle {
                id: lineWidth_2
                width: 10
                height: 10
                radius: 10
                color: "#bfbfbf"
                MouseArea {
                    anchors.fill: parent
                    onClicked: {
                        parent.color = "#1296db"
                        lineWidth_1.color = "#bfbfbf"
                        lineWidth_3.color = "#bfbfbf"
                        currentLineWidth = 4
                    }
                }
            }

            Rectangle {
                id: lineWidth_3
                width: 15
                height: 15
                radius: 15
                color: "#bfbfbf"
                MouseArea {
                    anchors.fill: parent
                    onClicked: {
                        parent.color = "#1296db"
                        lineWidth_1.color = "#bfbfbf"
                        lineWidth_2.color = "#bfbfbf"
                        currentLineWidth = 6
                    }
                }
            }

            Rectangle {
                width: 1
                height: 25
                color: "#e6e6e6"
            }

            Rectangle {
                id: color_1
                width: 15
                height: 15
                border.color: "black"
                border.width: 2
                color: "red"
                MouseArea {
                    anchors.fill: parent
                    onClicked: {
                        parent.border.width = 2
                        color_2.border.width = 0
                        color_3.border.width = 0
                        color_4.border.width = 0
                        color_5.border.width = 0
                        currentColor = "red"
                    }
                }
            }

            Rectangle {
                id: color_2
                width: 15
                height: 15
                border.color: "black"
                border.width: 0
                color: "yellow"
                MouseArea {
                    anchors.fill: parent
                    onClicked: {
                        parent.border.width = 2
                        color_1.border.width = 0
                        color_3.border.width = 0
                        color_4.border.width = 0
                        color_5.border.width = 0
                        currentColor = "yellow"
                    }
                }
            }

            Rectangle {
                id: color_3
                width: 15
                height: 15
                border.color: "black"
                border.width: 0
                color: "green"
                MouseArea {
                    anchors.fill: parent
                    onClicked: {
                        parent.border.width = 2
                        color_2.border.width = 0
                        color_1.border.width = 0
                        color_4.border.width = 0
                        color_5.border.width = 0
                        currentColor = "green"
                    }
                }
            }

            Rectangle {
                id: color_4
                width: 15
                height: 15
                border.color: "black"
                border.width: 0
                color: "#1296db"
                MouseArea {
                    anchors.fill: parent
                    onClicked: {
                        parent.border.width = 2
                        color_2.border.width = 0
                        color_3.border.width = 0
                        color_1.border.width = 0
                        color_5.border.width = 0
                        currentColor = "#1296db"
                    }
                }
            }

            Rectangle {
                id: color_5
                width: 15
                height: 15
                border.color: "black"
                border.width: 0
                color: "purple"
                MouseArea {
                    anchors.fill: parent
                    onClicked: {
                        parent.border.width = 2
                        color_2.border.width = 0
                        color_3.border.width = 0
                        color_4.border.width = 0
                        color_1.border.width = 0
                        currentColor = "purple"
                    }
                }
            }
        }
    }

    FileDialog {
        id: saveDialog
        property date nowDate: new Date()
        title: "另存为"
        fileMode: FileDialog.SaveFile
        nameFilters: ["png图像 (*.png)", "jpg图像 (*.jpg)", "jpeg图像 (*.jpeg)", "bmp图像 (*.bmp)", "所有文件 (*.*)"]
        onVisibleChanged: {
            saveDialog.currentFile = "file:///截图" + nowDate.getFullYear() + nowDate.getMonth() + 1 + nowDate.getDay() + generateShortUuid() + ".png" // 默认文件名
        }
        onAccepted: {
            var filePath = String(saveDialog.currentFile)
            if (Qt.platform.os === "windows") {
                filePath = filePath.substr(8) // 去掉 Windows 文件路径前缀
            }
            else {
                filePath = filePath.substr(7) //去掉Unix路径前缀
            }
            console.log("保存路径:", filePath)
            // 调用C++处理
            var nameFilter = saveDialog.selectedNameFilter
            g_screenShot.saveImageToFile(filePath, nameFilter)
            root.close()
        }
    }

    function generateShortUuid() {
        return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
            var r = Math.random() * 16 | 0,
                v = c === 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        });
    }

    function captureScreenshot(x, y, width, height) {
        g_screenShot.saveImageToClipboard(x, y, width, height)
    }
}
